<?php
/**
 * 
 * @todo Move these functions to TranslateController (?)
 */
class TranslateScript extends Script
{
	/// Extracts strings from source code.
	function extract()
	{
		Load::libs('files');
		$this->translations = array();
		
		# extracts string from source files
		$files = array();
		files::glob(APP,     'php|tpl', &$files);
		files::glob(FEATHER, 'php|tpl', &$files);
		$this->parse($files);
		
		# saves strings in database
		$now = Time::SQL();
		$db  = DBO::get();
		foreach(array_keys($this->translations) as $key)
		{
			$this->translations[$key]['id']      = $key;
			$this->translations[$key]['created'] = $now;
		}
		$db->replace_many('translate_strings', $this->translations);
		
		# removes old strings from database
		$where = array('created' => "< $now");
		$db->delete('translation_strings', $where);
	}
	
	/// Builds translation files.
	function build()
	{
		
	}
	
	/**
	 * Extracts message strings from a list of files.
	 * 
	 * @param $files Array
	 */
	private function & parse(array &$files)
	{
		foreach($files as $path)
		{
			# extracts PHP code from file, and removes comments
			$content = file_get_contents($path);
			$content = preg_replace(array(':(#|//)(.*):', ':/\*(.+?)\*/:s'), '', $content);
			
			preg_match_all('/<([%?])(?:php|)(.+?)\1>/s', $content, $phps, PREG_SET_ORDER);
			foreach($phps as $php)
			{
				# extracts translation functions from PHP code
				preg_match_all('/translate::[c]?(text|plural)\s*\((.+?)\)/s', $php[2], $messages, PREG_SET_ORDER);
				
				foreach($messages as $mesg)
				{
					# parses function arguments (careful of commas, quotes and single quotes)
					$args = preg_split('/[\s,]*[\"]([^\"]+)[\"][\s,]*|[\s,]*[\']([^\']+)[\'][\s,]*|[\s,]+/',
						trim($mesg[2]), 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
					$msg  = array();
					
					if ($mesg[1] == 'text')
					{
						# singular translation
						$msg['context'] = isset($args[1]) ? array_shift($args) : null;
					}
					else
					{
						# plural translation
						$msg['context'] = isset($args[3]) ? array_shift($args) : null;
						$msg['msgid_plural'] = $args[1];
					}
					$msg['msgid'] = $args[0];
					
					$key = sha1("context:{$msg['context']},msgid:{$msg['msgid']}");
					$this->translations[$key] = $msg;
				}
			}
		}
	}
}

?>